<?php

namespace app\common\model\xiluhouse;

use think\Model;
use traits\model\SoftDelete;

class HouseBuilding extends Base
{

    use SoftDelete;

    // 表名
    protected $name = 'xiluhouse_house_building';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'sale_state_text',
        'opentime_text',
        'deliverytime_text',
        'status_text',
    ];

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    public function getSaleStateList()
    {
        return ['1' => __('Sale_state 1'), '2' => __('Sale_state 2'), '3' => __('Sale_state 3')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Status normal'), 'hidden' => __('Status hidden')];
    }

    public function getSaleStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['sale_state']) ? $data['sale_state'] : '');
        $list = $this->getSaleStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getOpentimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['opentime']) ? $data['opentime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getDeliverytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['deliverytime']) ? $data['deliverytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setOpentimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDeliverytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function house()
    {
        return $this->belongsTo('House', 'house_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
